package com.dartfar.workflow.service;

import java.util.List;

import javax.annotation.Resource;

import net.sf.json.JSONObject;

import org.apache.log4j.Logger;
import org.jbpm.api.ExecutionService;
import org.jbpm.api.ProcessInstance;
import org.jbpm.api.TaskQuery;
import org.jbpm.api.TaskService;
import org.jbpm.api.task.Task;
import org.springframework.stereotype.Component;

import com.dartfar.base.dao.DaoUtil;
import com.dartfar.base.model.BaseEntity;
import com.dartfar.base.model.Person;
import com.dartfar.base.service.BaseServiceImpl;
import com.dartfar.util.EntityUtils;
import com.dartfar.workflow.constant.WorkflowEventType;
import com.dartfar.workflow.constant.WorkflowStatusVar;
import com.dartfar.workflow.constant.WorkflowDeployVar;
import com.dartfar.workflow.model.WorkflowEvents;
import com.dartfar.workflow.model.WorkflowProcessFunMount;

@Component("workflowProcessFunMountService")
public class WorkflowProcessFunMountServiceImpl extends BaseServiceImpl<WorkflowProcessFunMount> implements WorkflowProcessFunMountService {

	static Logger logger = Logger.getLogger(WorkflowProcessFunMountServiceImpl.class);

	
	@Resource
	private DaoUtil<WorkflowProcessFunMount> workflowProcessFunMountDaoUtil;
	@Resource
	private DaoUtil<BaseEntity> baseEntityDaoUtil;
	@Resource
	private ExecutionService executionService;
	@Resource
	private TaskService taskService;
	@Resource
	private WorkflowEventsService workflowEventsService;
	
	@Override
	public void startProcess(Person person, int wpfmId,  int id, JSONObject returnObj) {
		// TODO Auto-generated method stub
		logger.info("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa");
		String message;
		//判断流程是否存在
		logger.info("wpfmId: " + wpfmId);
		WorkflowProcessFunMount processFunMount = (WorkflowProcessFunMount) workflowProcessFunMountDaoUtil.get("from WorkflowProcessFunMount w where w.id = " + wpfmId);
		if(processFunMount == null){
			logger.info("此流程不存在.");
			returnObj.put("message", new String[]{"此流程不存在, 流程启动失败!"});
			return;
		}
		
		//获取流程Key
		String processKey = processFunMount.getProcessKey();
		
		//判断是否登录
		int currentPersonId = person.getPersonId();
		if(currentPersonId == 0){
			logger.info("当前没有登录.");
			returnObj.put("message", new String[]{"没有登录系统, 请登录后再进行操作!"});
			return;
		}
		ProcessInstance pi = executionService.startProcessInstanceByKey(processKey, String.valueOf(id));
		
		if(EntityUtils.isNotNull(pi)){
			String piId = pi.getId();
			String modelName = processFunMount.getModelName();
			String pdId = pi.getProcessDefinitionId();
			Class clazz = null;
			try {
				clazz = Class.forName(modelName);
			} catch (ClassNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			//更新业务实例
			BaseEntity entity = baseEntityDaoUtil.get(id, clazz);
			entity.setProcessId(String.valueOf(processFunMount.getId()));
			entity.setProcessDefinitionId(pdId);
			entity.setProcessInstanceId(piId);
			entity.setWorkflowStatus(WorkflowStatusVar.WAIT_STATUS);
			baseEntityDaoUtil.update(entity);
			 //业务对象主键
			logger.info("PDID: " + pi.getId() + "   BO_ID_VALUE: " + id);
			executionService.setVariable(pi.getId(), WorkflowDeployVar.BO_ID_VALUE, id);
			 //当前登录用户
			logger.info("PDID: " + pi.getId() + "   PI_OWNER: " + currentPersonId);
			executionService.setVariable(pi.getId(), WorkflowDeployVar.PI_OWNER, currentPersonId);
			//执行流程启动前事件，暂无实现，先在这里调用
			List<WorkflowEvents> processEvents = processFunMount.getWorkflowEvents();
			if(EntityUtils.isNotNull(processEvents) && processEvents.size() > 0){
				for(WorkflowEvents processEvent : processEvents){
					if(processEvent.getEventType().equalsIgnoreCase(WorkflowEventType.PROCESS_START)){
						//执行流程启动事件
						logger.info("这是流程启动事件。");
						workflowEventsService.execEventMethod(processEvent, entity);
						//wfEventManager.executeEventMethod(processEvent, entity);
					}
				}
			}
			executionService.setVariable(pi.getId(), WorkflowDeployVar.WITHDRAWUSER, currentPersonId);
		TaskQuery taskQuery = taskService.createTaskQuery();
			taskQuery.processInstanceId(piId);
			List<Task> tasks = taskQuery.list();
			for(Task task : tasks){
				executionService.setVariable(pi.getId(), WorkflowDeployVar.WITHDRAWUSER, currentPersonId);
				logger.info("TASKNAME: " + task.getName() + " TASKSSIGNE: " + task.getAssignee());
				task.setAssignee(String.valueOf(currentPersonId));
				//returnObj.put("taskId", task.getId());
				//returnObj.put(wfNext,WfButtons.BTN_SUBMIT);
				//returnObj.put(wfBack, WfButtons.BTN_TAKEBACK);
				//buildFormInfo(pdid,task.getName(),task.getId(),returnObj);
			}
			returnObj.put("message", new String[]{"流程启动成功."});
			return;
		}else{
			returnObj.put("message", new String[]{"流程启动失败."});
			return;
		}
	}

	@Override
	public void cancelProcess(String taskId, String modelName, String idValue) {
		// TODO Auto-generated method stub
		
	}

	/**
	 * 挂接流程
	 * @param workflowProcessFunMount
	 */
	@Override
	public void mountProcess(WorkflowProcessFunMount workflowProcessFunMount) {
		// TODO Auto-generated method stub
		WorkflowProcessFunMount process = (WorkflowProcessFunMount) workflowProcessFunMountDaoUtil.get("from WorkflowProcessFunMount w where w.id = " + workflowProcessFunMount.getId());
		process.setMountStatus(WorkflowStatusVar.MOUNTSTATUS_YES);
		workflowProcessFunMountDaoUtil.update(process);
	}

	/**
	 * 取消挂接流程
	 * @param workflowProcessFunMount
	 */
	@Override
	public void cancelMountProcess(WorkflowProcessFunMount workflowProcessFunMount) {
		// TODO Auto-generated method stub
		
		WorkflowProcessFunMount process = (WorkflowProcessFunMount) workflowProcessFunMountDaoUtil.get("from WorkflowProcessFunMount w where w.id = " + workflowProcessFunMount.getId());
		process.setMountStatus(WorkflowStatusVar.MOUNTSTATUS_NO);
		workflowProcessFunMountDaoUtil.update(process);
	}

}
